package com.hnao.hnaoprinterlib

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
import android.view.View
import android.widget.Toast
import com.gprinter.command.EscCommand
import com.gprinter.command.GpUtils
import com.gprinter.command.LabelCommand

/**
 * @Author caow
 * 2024/1/6
 */
object PrinterManager {

    private const val SP_PRINTER_MAC_ADDRESS = "sp_printer_mac_address"
    private const val id = 0
    private val threadPool = ThreadPool.getInstantiation()

    fun linkPrinter(context: Activity) {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id]!!.mPort != null) {
            return
        }
        if (!attemptBtUSBConnect(context)) {
            val sp = context.getSharedPreferences("sp_printer", Context.MODE_PRIVATE)
            val macAddress = sp.getString(SP_PRINTER_MAC_ADDRESS, null)
            if (!macAddress.isNullOrEmpty()) {
                attemptBtConnect(macAddress)
            } else {
                // 搜索蓝牙
                context.startActivityForResult(
                    Intent(context, BluetoothDeviceList::class.java),
                    Constant.BLUETOOTH_REQUEST_CODE
                )
            }
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constant.BLUETOOTH_REQUEST_CODE) {
                /*获取蓝牙mac地址*/
                val macAddress = data?.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS)
                if (macAddress != null) {
                    attemptBtConnect(macAddress)
                }
            }
        }
    }

    private fun printByOrder(
        printContentList: List<PrinterContentData>,
        width: Int = 80,
        height: Int = 100,
    ) {
        val tsc = LabelCommand()
        /* 设置标签尺寸，按照实际尺寸设置 */
//        tsc.addSize(80, 105)
        // 设置标签尺寸宽高，按照实际尺寸设置 单位mm
        tsc.addUserCommand("\r\n")
        tsc.addSize(width, height)
        /* 设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0 */
        tsc.addGap(0)
        /* 设置打印方向 */
        tsc.addDirection(LabelCommand.DIRECTION.FORWARD, LabelCommand.MIRROR.NORMAL)
        /* 开启带Response的打印，用于连续打印 */
//        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.ON)
        /* 设置原点坐标 */
        tsc.addReference(0, 20)
        /* 撕纸模式开启 */
        tsc.addTear(EscCommand.ENABLE.ON)
        /* 清除打印缓冲区 */
        tsc.addCls()
        /* 绘制简体中文 */

        for (item in printContentList) {
            when (item.type) {
                Constant.TYPE_TEXT -> {
                    tsc.addText(
                        item.x,
                        item.y,
                        item.font,
                        item.rotation,
                        item.xscal,
                        item.yscal,
                        item.text
                    )
                }

                Constant.TYPE_1D_BARCODE -> {
                    tsc.add1DBarcode(
                        item.x,
                        item.y,
                        LabelCommand.BARCODETYPE.CODE128,
                        50,
                        LabelCommand.READABEL.EANBEL,
                        LabelCommand.ROTATION.ROTATION_0,
                        item.text
                    )
                }
            }
        }

        /* 打印标签 */
        tsc.addPrint(1)
        /* 打印标签后 蜂鸣器响 */

        tsc.addSound(2, 100)
        tsc.addCashdrwer(LabelCommand.FOOT.F5, 255, 255)
        val datas = tsc.command
        /* 发送数据 */
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null) {
            Log.i("caow", "sendLabel: 打印机为空")
            return
        }
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas)
    }

    /**
     * 打印标签 (贴纸)
     * 尺寸 100mm * 80mm
     */
    private fun printByView(view: View) {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[0] == null || !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[0].connState) {
            Toast.makeText(PrinterApp.context, "打印机未连接", Toast.LENGTH_SHORT).show()
            return
        }

        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[0] != null
            && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[0].currentPrinterCommand == PrinterCommand.TSC
        ) {
            view.measure(
                View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY)
            )
            view.layout(0, 0, view.measuredWidth, view.measuredHeight)
            var bmp: Bitmap =
                Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
            val c = Canvas(bmp)
            c.drawColor(Color.WHITE)
            view.draw(c)
            val matrix = Matrix()
            matrix.setRotate(270f)
            bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)

            val labelCommand = LabelCommand()
            labelCommand.addSize(100, 80)
            labelCommand.addGap(3)
            labelCommand.addDirection(
                LabelCommand.DIRECTION.BACKWARD,
                LabelCommand.MIRROR.NORMAL
            )
            labelCommand.addReference(0, 0)
            labelCommand.addCls()
            labelCommand.addDensity(LabelCommand.DENSITY.DNESITY7)

//        val rszBitmap: Bitmap = GpUtils.resizeImage(bmp, bmp.width, bmp.height)
            val bytes: ByteArray =
                GpUtils.printTscDraw(0, 0, LabelCommand.BITMAP_MODE.OVERWRITE, bmp)
            for (i in bytes.indices) {
                labelCommand.command.add(java.lang.Byte.valueOf(bytes[i]))
            }
            labelCommand.addStrToCommand("\r\n", "GB2312")

//            labelCommand.add1DBarcode(
//                618,
//                363,
//                LabelCommand.BARCODETYPE.CODE128,
//                80,
//                LabelCommand.READABEL.EANBEL,
//                LabelCommand.ROTATION.ROTATION_270,
//                dto.box.barCode ?: ""
//            )
//
//            labelCommand.addQRCode(
//                22,
//                240,
//                LabelCommand.EEC.LEVEL_L,
//                7,
//                LabelCommand.ROTATION.ROTATION_270,
//                getString(R.string.str_jxhuali)
//            )

            labelCommand.addPrint(1)
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[0].sendDataImmediatelyAsync(
                labelCommand.command
            )
        }
    }


    /**
     * 重新连接回收上次连接的对象，避免内存泄漏
     */
    private fun closeport() {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort != null) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id)
            //            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort.closePort();
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort = null;
        }
    }

    private fun attemptBtUSBConnect(context: Context): Boolean {
        // 先尝试USB连接
        val manager = PrinterApp.context.getSystemService(Context.USB_SERVICE) as UsbManager
        val deviceList = manager.deviceList
        val deviceIterator = deviceList.values.iterator()
        while (deviceIterator.hasNext()) {
            val device = deviceIterator.next()
            if (!checkUsbDevicePidVid(device)) {
                deviceIterator.remove()
            }
        }
        if (deviceList.size == 1) {
            closeport()
            for (it in deviceList.values) {
                DeviceConnFactoryManager.Build()
                    .setId(id)
                    .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.USB)
                    .setUsbDevice(it)
                    .setContext(context)
                    .build()
                threadPool.addTask {
                    DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort()
                }
            }
            return true
        }
        return false
    }


    private fun attemptBtConnect(macAddress: String) {
//        if (macAddress == null) {
//            macAddress = mSp.getString(AppConfig.PRINTER_BT_ADDRESS, null)
//            if (TextUtils.isEmpty(macAddress)) {
//                return
//            }
//        }
        /* 初始化话DeviceConnFactoryManager */
        closeport()
        DeviceConnFactoryManager.Build()
            .setId(id) /* 设置连接方式 */
            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH) /* 设置连接的蓝牙mac地址 */
            .setMacAddress(macAddress)
            .build()
        /* 打开端口 */Log.i("caow", "onActivityResult: 连接蓝牙$id")
        //        threadPool = ThreadPool.getInstantiation();
        threadPool.addTask {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort()
        }
    }

    private fun checkUsbDevicePidVid(dev: UsbDevice): Boolean {
        val pid = dev.productId
        val vid = dev.vendorId
        return (vid == 34918 && pid == 256 || vid == 1137 && pid == 85
                || vid == 6790 && pid == 30084
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 512
                || vid == 26728 && pid == 768
                || vid == 26728 && pid == 1024 || vid == 26728 && pid == 1280
                || vid == 26728 && pid == 1536)
    }

}